package com.hosever.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import com.hosever.exceptions.SeverSecurityException;
/**
 * Sever安全算法
 * @author Sever
 * @history Sever 2014-06-24 14:08
 */
public class SeverSecurity {
	/**
	 * sever加密算法
	 * @param s
	 * @return
	 * @throws NoSuchAlgorithmException
	 */
	public static String severEncrypt(String s) throws NoSuchAlgorithmException{
		String source = SeverSecurity.MD516(SeverSecurity.MD532(s));
		//加盐
		String salt = "2b2b2b";
		String s1 = source.substring(0, 3);
		String s2 = source.substring(3,6);
		String s3 = source.substring(6,source.length());
		
		String salt1 = salt.substring(0,3);
		String salt2 = salt.substring(3,6);
//		System.out.println(source);
//		System.out.println(s1+salt1+s2+salt2+s3);
		return s1+salt1+s2+salt2+s3;
	}
	/**
	 * sever解密算法
	 * @param s
	 * @return
	 * @throws SeverSecurityException 
	 */
	public static String severDecipher(String s) throws SeverSecurityException{
		if(s.length()<12){
			throw new SeverSecurityException("解密器异常：解密算法源字符串长度<12");
		}
		String s1 = s.substring(0,3);
		String s2 = s.substring(6,9);
		String s3 = s.substring(12,s.length());
		return s1+s2+s3;
	}
	/**
	 * MD5 32位加密算法
	 * @param s
	 * @return
	 * @throws NoSuchAlgorithmException
	 */
	public static String MD532(String s) throws NoSuchAlgorithmException{
		MessageDigest md5 = MessageDigest.getInstance("MD5");
		md5.update(s.getBytes()); 
		byte b[] = md5.digest(); 
		
			int i; 
		StringBuffer buf = new StringBuffer(""); 
		for (int offset = 0; offset < b.length; offset++) { 
			i = b[offset]; 
			if(i<0){i+= 256;} 
			if(i<16){buf.append("0");}
			buf.append(Integer.toHexString(i)); 
		} 
		return buf.toString();
	}
	/**
	 * MD5 16位加密算法
	 * @param s
	 * @return
	 * @throws NoSuchAlgorithmException
	 */
	public static String MD516(String s) throws NoSuchAlgorithmException{
		MessageDigest md5 = MessageDigest.getInstance("MD5");
		md5.update(s.getBytes()); 
		byte b[] = md5.digest(); 
		
		int i; 
		StringBuffer buf = new StringBuffer(""); 
		for (int offset = 0; offset < b.length; offset++) { 
			i = b[offset]; 
			if(i<0){i+= 256;} 
			if(i<16){buf.append("0");}
			buf.append(Integer.toHexString(i)); 
		} 
		return buf.toString().substring(8,24);
	}
}
